package com.stock.stockana.requests;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.stock.stockana.beans.PushRecord;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.network.GetAllStocksEvent;
import com.stock.stockana.events.network.GetPushRecordEvent;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;


/**
 * ---------------------------------------------------
 * Description: 获取yong用户所有的股票推送记录
 * Author: ljgsonx
 * Belong to: com.wds.stock.stockana.requests
 * Time: 2016/1/15 17:42
 * ---------------------------------------------------
 */
public class GetPushRecord extends BaseStringRequest<GetPushRecord> {

    private final static String TAG = "GetPushRecord--->";
    public static List<PushRecord> pushRecords = new ArrayList<>();

    private GetPushRecord(){
        super(Method.GET, NetWorkConstants.GET_PUSHRECORD_URL, listener, errorListener);
        Log.d(TAG, NetWorkConstants.GET_PUSHRECORD_URL);
    }

    public static GetPushRecord build() {
        return new GetPushRecord();
    }

    static Response.Listener<String> listener = new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
            if ("[".charAt(0) == response.charAt(0)) {
                List<PushRecord> tempRecords = JSON.parseArray(response, PushRecord.class);
                pushRecords.clear();
                pushRecords.addAll(tempRecords);
                EventBus.getDefault().post(new GetPushRecordEvent(NetWorkConstants.RESPONSE_CODE_OK, null));
            } else if ("{".charAt(0) == response.charAt(0)) {
                ResponseBean rb = JSON.parseObject(response, ResponseBean.class);
                EventBus.getDefault().post(new GetPushRecordEvent(NetWorkConstants.RESPONSE_CODE_ERROR, NetWorkConstants.RESPONSE_ERROR2 + rb.getErrorMsg()));
            } else {
                EventBus.getDefault().post(new GetPushRecordEvent(NetWorkConstants.RESPONSE_CODE_ERROR, NetWorkConstants.RESPONSE_ERROR1 + response));
            }
        }
    };

    static Response.ErrorListener errorListener = new Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            EventBus.getDefault().post(new GetAllStocksEvent(NetWorkConstants.RESPONSE_CODE_ERROR, NetWorkConstants.RESPONSE_ERROR3 + error.toString()));
        }
    };

}
